package com.hyh.spring.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @BelongsPackage: com.hyh.spring.lb
 * @ClassName MyLB
 * @Author: hyhWTX
 * @CreateTime: 2023-04-13  16:55
 * @Description: TODO (一句话描述以下该类的功能)
 * @Version: 1.0
 */
@Component
public class MyLB implements LoadBalancer{
    //仿源码。原子类
    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    //思想：模仿产生自旋锁
    private final int getAndIncrement(){
        int current;
        int next;
        //使用do...while完成自旋锁
        do {
            current= this.atomicInteger.get();
            next = current>=Integer.MAX_VALUE?0:current+1;

        }
        //若没有找到，则一直自旋，直到找到我们想要的值
        while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("*****第几次访问，次数next: "+next);
        return  next;
    }
    //负载均衡算法：rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标  ，每次服务重启动后rest接口计数从1开始。
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstance) {
        int index = getAndIncrement() % serviceInstance.size();
        return serviceInstance.get(index);
    }
}
